import { Provide, Inject } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from 'midwayjs-cool-core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { Context } from 'egg';
import { PickWareHourseEntity } from '../../entity/warehouse';
import { OrderEntity } from '../../entity/order';
import { PickWareHourseLogEntity } from '../../entity/warehouselogs';
import * as moment from 'moment';

/**
 * 拣货单
 */
@Provide()
export class WarehouseService extends BaseService {
  @InjectEntityModel(OrderEntity)
  OrderEntity: Repository<OrderEntity>;

  @InjectEntityModel(PickWareHourseLogEntity)
  PickWareHourseLogEntity: Repository<PickWareHourseLogEntity>; // 备注

  @InjectEntityModel(PickWareHourseEntity)
  PickWareHourseEntity: Repository<PickWareHourseEntity>; //库存

  @Inject()
  warehouseService: WarehouseService; // 捡货单

  @Inject()
  ctx: Context;
  async add(params) {
    const select = `select * from pick_warehouse where barCode = "${params.barCode}" and orderId = "${Number(params.orderId)}"`;
    const item = await this.nativeQuery(select);
    if (item.length > 0) {
      throw new CoolCommException('已存在此条资产编号');
    }
    if (Number(params.realNum) > Number(params.quantityNum)) {
      throw new CoolCommException('出库数量不能大于库存数量');
    }
    const data = await this.PickWareHourseEntity.insert(params);

    const newOrder: any = await this.OrderEntity.findOne({
      id: params.orderId,
    });
    const logs = {
      realNum: params.realNum,
      quantityNum: params.quantityNum,
      barCode: params.barCode,
      orderId: params.orderId,
      specifications: params.specifications,
      orderName: params.warname,
      kuweiName: newOrder.name,
    };
    this.PickWareHourseLogEntity.save(logs);
    return { message: '新增成功', code: 1000, data: data };
  }
  async update(param): Promise<any> {
    if (Number(param.realNum) > Number(param.quantityNum)) {
      throw new CoolCommException('出库数量不能大于库存数量');
    }
    if (!param.id) {
      const select = `select * from pick_warehouse where barCode = "${param.barCode}" and orderId = "${Number(param.orderId)}"`;
      const item = await this.nativeQuery(select);
      if (item.length === 0) {
        if(Number(param.realNum) > 0) {
          throw new CoolCommException('该资产不存在,不能出库');
        }
        return await this.add(param);
      } else {
        if(Number(param.realNum) > 0 && Number(item[0].quantityNum)===0 || (Number(param.realNum)+Number(item[0].realNum)) > Number(item[0].quantityNum)) {
          throw new CoolCommException('出库数量不能大于库存数量');
        }
        param.id = item[0].id;
      }
    }
    const info = await this.info(param.id);
    const order: any = await this.OrderEntity.findOne({ id: info.orderId });
    info.kuweiName = order.name;
    const { url } = this.ctx;
    // 如果是api，就直接+1
    if (new RegExp('/api/').test(url)) {
      if (param.realNum) {
        param.realNum = Number(info.realNum) + Number(param.realNum || 0);
      } else {
        param.realNum = info.realNum;
      }
      if (param.quantityNum) {
        param.quantityNum =
          Number(info.quantityNum) + Number(param.quantityNum || 0);
      } else {
        param.quantityNum = info.quantityNum;
      }
    }
    await this.addLogs(info, param);
    info.realNum = Number(param.realNum);
    info.quantityNum = Number(param.quantityNum);
    info.orderId = Number(param.orderId);
    info.warname = param.warname;
    info.specifications = param.specifications;
    try {
      const data: any = await this.PickWareHourseEntity.save(info);
      return new Promise(resolve => {
        resolve({ message: '修改成功', code: 1000, data: data });
      });
    } catch (error) {
      throw new CoolCommException('保存失败，请检查是否有此库存');
    }
  }
  async addLogs(info, param) {
    let updateTime = 'NOW()';
    const { url } = this.ctx;
    // 如果是api，就直接+1
    if (new RegExp('/api/').test(url)) {
      updateTime = param.updateTime
        ? moment(param.updateTime).format('YYYY-MM-DD')
        : 'NOW()';
    }
    const select = `SELECT DISTINCT * FROM pick_warehouse_log WHERE TO_DAYS(updateTime) = TO_DAYS('${updateTime}') AND barCode = '${info.barCode}';`;
    const logs = await this.nativeQuery(`${select}`);
    const realNum = Number(param.realNum) - Number(info.realNum);
    const quantityNum = Number(param.quantityNum) - Number(info.quantityNum);
    if (realNum === 0 && quantityNum === 0) {
      return;
    }
    const item: any = {
      realNum,
      quantityNum,
      barCode: info.barCode,
      orderId: Number(info.orderId),
      specifications: info.specifications,
      orderName: info.warname,
      kuweiName: info.kuweiName,
    };
    if (logs && logs.length > 0) {
      item.realNum = logs[0].realNum + item.realNum;
      item.quantityNum = logs[0].quantityNum + item.quantityNum;
      item.id = logs[0].id;
    }
    console.log(item,">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
    try {
      const save = await this.PickWareHourseLogEntity.save(item);
      return save;
    } catch (error) {
      throw new CoolCommException('保存失败，请检查是否有此库存');
    }
  }
}
